using System;
using Newtonsoft.Json;

namespace LeetCodeQuestionBank.Models
{
    public static class ListNodeExtend
    {
        /// <summary>
        /// 链表节点默认间隔字符串
        /// </summary>
        public const string LISTNODE_DEFAULT_INTERVAL = "->";

        /// <summary>
        /// 字符串转为链表节点
        /// </summary>
        /// <param name="nodeStr">链表节点表示字符串</param>
        /// <param name="interval">区分链表节点的间隔字符串</param>
        /// <param name="defalutNodeValue">默认节点的值</param>
        /// <returns></returns>
        public static ListNode ToListNode(this string nodeStr, string interval = LISTNODE_DEFAULT_INTERVAL, int defalutNodeValue = 0)
        {
            if (string.IsNullOrWhiteSpace(nodeStr))
            {
                return null;
            }
            string[] lists = nodeStr.Split(interval);
            ListNode head = new ListNode(0);
            ListNode result = head;
            int n = lists.Length;
            for (int i = 0; i < n; i++)
            {
                string str = lists[i];
                if (!int.TryParse(str, out int value))
                {
                    if (str.ToLower() == @"null" && i == n - 1)
                    {
                        break;
                    }
                    value = defalutNodeValue;
                };
                head.next = new ListNode(value);
                head = head.next;
            }
            return result.next;
        }
    }
}
